package ias.deepsearch.com.helper.ui.view;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.socks.library.KLog;
import com.yancloud.android.reflection.get.YanCloudGet;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import ias.deepsearch.com.helper.R;
import ias.deepsearch.com.helper.util.normal.FloatWindowManager;

public class AssistTouchViewLayout extends LinearLayout {
	public static ExecutorService executor = Executors.newFixedThreadPool(5);

	//记录小悬浮窗的宽度
	public static int viewWidth;

	//记录小悬浮窗的高度
	public static int viewHeight;

	//记录系统状态栏的高度
	 private static int statusBarHeight;

	//用于更新小悬浮窗的位置
	private WindowManager windowManager;

	//小悬浮窗的参数
	private WindowManager.LayoutParams mParams;

	//记录当前手指位置在屏幕上的横坐标值
	private float xInScreen;

	//记录当前手指位置在屏幕上的纵坐标值
	private float yInScreen;

	//记录手指按下时在屏幕上的横坐标的值
	private float xDownInScreen;

	//记录手指按下时在屏幕上的纵坐标的值
	private float yDownInScreen;

	//记录手指按下时在小悬浮窗的View上的横坐标的值
	private float xInView;

	//记录手指按下时在小悬浮窗的View上的纵坐标的值
	private float yInView;

	Context context;

	TextView percentView;


	String addr;

	View view;

	public AssistTouchViewLayout(final Context context) {
		super(context);
		this.context = context;
		windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		LayoutInflater.from(context).inflate(R.layout.float_window_assist, this);
		view = findViewById(R.id.small_window_layout);
		viewWidth = view.getLayoutParams().width;
		viewHeight = view.getLayoutParams().height;
		percentView = (TextView) findViewById(R.id.percent);
		//percentView.setText(FloatWindowManager.getUsedPercentValue(context));
		percentView.setText("0");

		view.findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				percentView.setVisibility(View.VISIBLE);
				view.findViewById(R.id.big_window_layout).setVisibility(View.GONE);
			}
		});

		//滴滴
		view.findViewById(R.id.didi_ll).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				hideBigWindow();

				AssistTouchViewLayout.this.post(new Runnable() {
					@Override
					public void run() {
						startActivityLL("com.sdu.didi.psnger");
						//	AssistTouchViewLayout.this.context.getApplicationContext().startActivity(intent);
						executor.execute(new DidiMonitor(addr,true));

					}
				});
			}
		});

		//首气
		view.findViewById(R.id.sq_ll).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				hideBigWindow();
				final Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				ComponentName cn = new ComponentName("com.ichinait.gbpassenger", "com.ichinait.gbpassenger.main.MainActivity");
				intent.setComponent(cn);
				AssistTouchViewLayout.this.post(new Runnable() {
					@Override
					public void run() {
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivityLL("com.ichinait.gbpassenger");
						//	AssistTouchViewLayout.this.context.getApplicationContext().startActivity(intent);
						executor.execute(new DidiMonitor(addr,false));

					}
				});
			}
		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
			xInView = event.getX();
			yInView = event.getY();
			xDownInScreen = event.getRawX();
			yDownInScreen = event.getRawY() - getStatusBarHeight();
			xInScreen = event.getRawX();
			yInScreen = event.getRawY() - getStatusBarHeight();
			break;
		case MotionEvent.ACTION_MOVE:
			xInScreen = event.getRawX();
			yInScreen = event.getRawY() - getStatusBarHeight();
			// 手指移动的时候更新小悬浮窗的位置
			updateViewPosition();
			break;
		case MotionEvent.ACTION_UP:
			// 如果手指离开屏幕时，xDownInScreen和xInScreen相等，且yDownInScreen和yInScreen相等，则视为触发了单击事件。
			if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
				executor.execute(new Runnable(){

					@Override
					public void run() {
						detectAndStartDidi();
					}
				});

			}
			break;
		default:
			break;
		}
		return true;
	}

	private void detectAndStartDidi() {
		final String addr = isDianpingAddress();
		this.addr = addr;
		if (addr!=null&& !addr.contains("errorCode") && !addr.contains("false")){
			Log.d("AssisTouchView",addr);

			openBigWindow();

		}
	}
	public void startActivityLL(String packagename){
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(packagename, 0);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            KLog.v("liuyi", "cannot find target package : " + packagename);
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);


// 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = context.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;

            //TODO 需要把Xposed模块中的launchActivity也设置为这个
            //KLog.v("liuyi", "package: " + packageName + " ,launchActivity: " + className);



            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }

    }
	static class DidiMonitor implements Runnable{
		private final boolean isDidi;
		private  String addr;

		DidiMonitor(String addr,boolean isDidi){
			this.addr = addr;
			this.isDidi = isDidi;
		}
		public void run(){
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String pkg = "com.ichinait.gbpassenger";
			if (isDidi)
				pkg = "com.sdu.didi.psnger";
			YanCloudGet api = new YanCloudGet("127.0.0.1");
			String action =			"{\"type\":\"click\",\"node\":{\"resource_id\":\"home_normal_end_address_layout\"}}";
			if (isDidi)
				action = "{\"type\":\"click\",\"node\":{\"resource_id\":\"bt5\"}}";
			String ret = (String) api.get(pkg, "performAction", action);
			Log.d("Assist,Ret1",ret);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			addr = encode(addr);
			action  = "{\"type\":\"input\",\"node\":{\"resource_id\":\"location_pick_edt_search_input\"},\"value\":\"";
			if (isDidi)
				action = "{\"type\":\"input\",\"node\":{\"resource_id\":\"c2x\"},\"value\":\"";

			action+=addr+"\"}";

			ret = (String) api.get(pkg, "performAction", action);
			Log.d("Assist,Ret2",ret);

		}

		private String encode(String addr) {
			return URLEncoder.encode(addr);
		}

	}
	private String isDianpingAddress() {
		YanCloudGet api = new YanCloudGet("127.0.0.1");
		String action ="{\"type\":\"getval\",\"node\":{\"xpath\":\"PhoneWindow$DecorView/LinearLayout/FrameLayout/FrameLayout/FrameLayout/RelativeLayout/MyScrollView/LinearLayout/GroupAgentFragment$CellContainer/CommonCell/LinearLayout/TextView\"}}";
		String ret = (String) api.get("com.dianping.v1", "performAction", action);
		if ("false".equals(ret))
			return null;
		return ret;
	}

	/**
	 * 将小悬浮窗的参数传入，用于更新小悬浮窗的位置。
	 * 
	 * @param params
	 *            小悬浮窗的参数
	 */
	public void setParams(WindowManager.LayoutParams params) {
		mParams = params;
	}

	/**
	 * 更新小悬浮窗在屏幕中的位置。
	 */
	private void updateViewPosition() {
		mParams.x = (int) (xInScreen - xInView);
		mParams.y = (int) (yInScreen - yInView);
		windowManager.updateViewLayout(this, mParams);
	}

	/**
	 * 打开大悬浮窗，同时关闭小悬浮窗。
	 */
	private void openBigWindow() {
//		FloatWindowManager.createBigWindow(getContext());
//		FloatWindowManager.removeSmallWindow(getContext());
		this.post(new Runnable() {
			@Override
			public void run() {
				view.findViewById(R.id.percent).setVisibility(View.GONE);
				view.findViewById(R.id.big_window_layout).setVisibility(View.VISIBLE);
				TextView tv = (TextView)view.findViewById(R.id.addr);
				tv.setText("检测到地址:\n"+addr);
			}
		});
	}


	void hideBigWindow(){
		this.post(new Runnable() {
			@Override
			public void run() {
				view.findViewById(R.id.percent).setVisibility(View.VISIBLE);
				view.findViewById(R.id.big_window_layout).setVisibility(View.GONE);
			}
		});
	}

	/**
	 * 用于获取状态栏的高度。
	 * 
	 * @return 返回状态栏高度的像素值。
	 */
	private int getStatusBarHeight() {
		if (statusBarHeight == 0) {
			try {
				Class<?> c = Class.forName("com.android.internal.R$dimen");
				Object o = c.newInstance();
				Field field = c.getField("status_bar_height");
				int x = (Integer) field.get(o);
				statusBarHeight = getResources().getDimensionPixelSize(x);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusBarHeight;
	}

}
